{% extends "line_base.html" %}

{% block title %}爱国情感分析结果{% endblock %}

{% block content %}
<div class="layui-container" style="padding: 20px;">
    <div class="layui-row">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h2>爱国情感分析结果</h2>
                    <p>爱国情感分析结果展示</p>
                </div>
                <div class="layui-card-body">
                    <!-- 统计信息 -->
                    <div class="layui-row">
                        <div class="layui-col-md3">
                            <div class="layui-card">
                                <div class="layui-card-body" style="text-align: center;">
                                    <h4>总分析数量</h4>
                                    <p style="font-size: 24px; color: #1E9FFF;">{{ total_count }}</p>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="layui-card">
                                <div class="layui-card-body" style="text-align: center;">
                                    <h4>平均爱国情感得分</h4>
                                    <p style="font-size: 24px; color: #5FB878;">{{ "%.1f"|format(avg_score * 100) }}%
                                    </p>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="layui-card">
                                <div class="layui-card-body" style="text-align: center;">
                                    <h4>平均评分</h4>
                                    <p style="font-size: 24px; color: #FFB800;">{{ "%.1f"|format(avg_grade) }}</p>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="layui-card">
                                <div class="layui-card-body" style="text-align: center;">
                                    <h4>操作</h4>
                                    <button class="layui-btn layui-btn-sm" onclick="exportResults()">
                                        <i class="layui-icon layui-icon-download-circle"></i> 导出结果
                                    </button>
                                    <button class="layui-btn layui-btn-sm layui-btn-normal"
                                        onclick="window.location.href='/patriotic_prompt/'">
                                        <i class="layui-icon layui-icon-return"></i> 返回主页
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 等级分布 -->
                    <div class="layui-row" style="margin-top: 20px;">
                        <div class="layui-col-md6">
                            <div class="layui-card">
                                <div class="layui-card-header">
                                    <h3>爱国情感等级分布</h3>
                                </div>
                                <div class="layui-card-body">
                                    <div class="layui-row">
                                        {% for level, count in level_distribution.items() %}
                                        <div class="layui-col-md6" style="margin-bottom: 10px;">
                                            <div class="layui-card">
                                                <div class="layui-card-body" style="text-align: center;">
                                                    <h5>{{ level }}</h5>
                                                    <p style="font-size: 20px; color: #1E9FFF;">{{ count }}人</p>
                                                </div>
                                            </div>
                                        </div>
                                        {% endfor %}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-card">
                                <div class="layui-card-header">
                                    <h3>分布图表</h3>
                                </div>
                                <div class="layui-card-body">
                                    <div id="chartContainer" style="height: 300px;"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 详细结果表格 -->
                    <div class="layui-row" style="margin-top: 20px;">
                        <div class="layui-col-md12">
                            <div class="layui-card">
                                <div class="layui-card-header">
                                    <h3>详细分析结果</h3>
                                </div>
                                <div class="layui-card-body">
                                    <table class="layui-table" lay-skin="line">
                                        <thead>
                                            <tr>
                                                <th>学生姓名</th>
                                                <th>学号</th>
                                                <th>班级</th>
                                                <th>爱国情感得分</th>
                                                <th>爱国情感等级</th>
                                                <th>是否具有爱国情感</th>
                                                <th>爱国词汇数量</th>
                                                <th>反爱国词汇数量</th>
                                                <th>分析置信度</th>
                                                <th>评分</th>
                                                <th>分析时间</th>
                                                <th>详细分析</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {% for analysis in analyses %}
                                            <tr>
                                                <td>{{ analysis.upload_homework.student.name }}</td>
                                                <td>{{ analysis.upload_homework.student.ID }}</td>
                                                <td>{{ analysis.upload_homework.student.class_id1 }}</td>
                                                <td>
                                                    <div class="layui-progress layui-progress-sm"
                                                        lay-showpercent="true">
                                                        <div class="layui-progress-bar" lay-percent="{{ "
                                                            %.1f"|format(analysis.patriotic_score * 100) }}%"></div>
                                                    </div>
                                                </td>
                                                <td>
                                                    {% if analysis.patriotic_level == "非常强烈爱国情感" %}
                                                    <span class="layui-badge layui-bg-red">{{ analysis.patriotic_level
                                                        }}</span>
                                                    {% elif analysis.patriotic_level == "较强爱国情感" %}
                                                    <span class="layui-badge layui-bg-orange">{{
                                                        analysis.patriotic_level }}</span>
                                                    {% elif analysis.patriotic_level == "一般爱国情感" %}
                                                    <span class="layui-badge layui-bg-blue">{{ analysis.patriotic_level
                                                        }}</span>
                                                    {% elif analysis.patriotic_level == "较弱爱国情感" %}
                                                    <span class="layui-badge layui-bg-gray">{{ analysis.patriotic_level
                                                        }}</span>
                                                    {% else %}
                                                    <span class="layui-badge">{{ analysis.patriotic_level }}</span>
                                                    {% endif %}
                                                </td>
                                                <td>
                                                    {% if analysis.is_patriotic %}
                                                    <span class="layui-badge layui-bg-green">是</span>
                                                    {% else %}
                                                    <span class="layui-badge layui-bg-red">否</span>
                                                    {% endif %}
                                                </td>
                                                <td>{{ analysis.patriotic_words_count }}</td>
                                                <td>{{ analysis.anti_patriotic_words_count }}</td>
                                                <td>{{ "%.1f"|format(analysis.confidence * 100) }}%</td>
                                                <td>
                                                    <div class="layui-form">
                                                        <input type="number" class="layui-input"
                                                            style="width: 80px; display: inline-block;"
                                                            value="{{ analysis.grade or '' }}" min="0" max="100"
                                                            placeholder="评分"
                                                            onchange="updateGrade({{ analysis.ID }}, this.value)">
                                                    </div>
                                                </td>
                                                <td>{{ analysis.analysis_time.strftime('%Y-%m-%d %H:%M:%S') if
                                                    analysis.analysis_time else '-' }}</td>
                                                <td>
                                                    <button class="layui-btn layui-btn-xs"
                                                        onclick="showDetail('{{ analysis.patriotic_breakdown }}', '{{ analysis.upload_homework.student.name }}', '{{ analysis.patriotic_level }}', '{{ analysis.patriotic_score }}', '{{ analysis.patriotic_words_count }}', '{{ analysis.anti_patriotic_words_count }}', '{{ analysis.confidence }}')">
                                                        查看详情
                                                    </button>
                                                </td>
                                            </tr>
                                            {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="/static/echarts.min.js"></script>
<script>
    layui.use(['element', 'layer', 'form'], function () {
        var element = layui.element;
        var layer = layui.layer;
        var form = layui.form;

        // 显示详细分析
        window.showDetail = function (content, studentName, level, score, patrioticWords, antiPatrioticWords, confidence) {
            var detailContent = `
                <div style="padding: 20px;">
                    <h4>${studentName} 的爱国情感分析详情</h4>
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <p><strong>学生姓名：</strong>${studentName}</p>
                            <p><strong>爱国情感等级：</strong>${level}</p>
                            <p><strong>爱国情感得分：</strong>${(score * 100).toFixed(1)}%</p>
                            <p><strong>爱国词汇数量：</strong>${patrioticWords}</p>
                        </div>
                        <div class="layui-col-md6">
                            <p><strong>反爱国词汇数量：</strong>${antiPatrioticWords}</p>
                            <p><strong>分析置信度：</strong>${(confidence * 100).toFixed(1)}%</p>
                            <p><strong>分析时间：</strong>${new Date().toLocaleString()}</p>
                        </div>
                    </div>
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">详细分析：</label>
                        <div class="layui-input-block">
                            <textarea readonly style="height: 150px;">${content}</textarea>
                        </div>
                    </div>
                </div>
            `;

            layer.open({
                type: 1,
                title: '详细分析',
                area: ['700px', '500px'],
                content: detailContent
            });
        };

        // 导出结果
        window.exportResults = function () {
            var homeworkId = window.location.pathname.split('/').pop();
            layer.msg('正在生成导出文件...', { icon: 16, time: 0 });

            $.get('/patriotic_prompt/export_results/' + homeworkId, function (res) {
                layer.closeAll();
                if (res.success) {
                    // 创建下载链接
                    var link = document.createElement('a');
                    link.href = res.download_url;
                    link.download = '';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    layer.msg('导出成功！', { icon: 1 });
                } else {
                    layer.msg('导出失败', { icon: 2 });
                }
            });
        };

        // 更新评分
        window.updateGrade = function (analysisId, grade) {
            if (grade < 0 || grade > 100) {
                layer.msg('评分必须在0-100之间', { icon: 2 });
                return;
            }

            $.ajax({
                url: '/patriotic_prompt/update_grade',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    analysis_id: analysisId,
                    grade: parseInt(grade)
                }),
                success: function (response) {
                    if (response.success) {
                        layer.msg('评分更新成功', { icon: 1 });
                    } else {
                        layer.msg('评分更新失败: ' + response.message, { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    layer.msg('评分更新失败，请稍后重试', { icon: 2 });
                }
            });
        };

        // 初始化图表
        function initChart() {
            var chartContainer = document.getElementById('chartContainer');
            if (!chartContainer) return;

            var chart = echarts.init(chartContainer);

            var levelData = {{ level_distribution | tojson }};
    var chartData = [];
    var colors = ['#ff5722', '#ff9800', '#2196f3', '#4caf50', '#9c27b0'];
    var colorIndex = 0;

    for (var level in levelData) {
        chartData.push({
            name: level,
            value: levelData[level],
            itemStyle: {
                color: colors[colorIndex % colors.length]
            }
        });
        colorIndex++;
    }

    var option = {
        title: {
            text: '爱国情感等级分布',
            left: 'center',
            textStyle: {
                fontSize: 16
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c}人 ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            data: chartData.map(item => item.name)
        },
        series: [
            {
                name: '人数',
                type: 'pie',
                radius: '50%',
                center: ['50%', '60%'],
                data: chartData,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };

    chart.setOption(option);

    // 窗口大小改变时重新调整图表
    window.addEventListener('resize', function () {
        chart.resize();
    });
        }

    // 页面加载完成后初始化图表
    setTimeout(initChart, 100);
    });
</script>
{% endblock %}